{% extends "map/index.html"%}
{% load staticfiles %}
{% block window %}
<html>
<head>
    <meta http-equiv="Content-Type" content="text/event-stream; charset=utf-8" />
</head>
<body>
<div class="container-fluid">
    <div class="col-md-2">
        <div class="alert alert-warning" role="alert">
            <h4>历史数据界面:</h4>
            对应船只，对应引擎，对应监控仪的历史信息。<br/>主要包含船速、水温、油温、以及监控仪得到的具有表现价值的所有数据。
        </div>
        <button onclick="select('{{history_data.0.ship_id}}', 'oneday')" class="btn btn-info">oneday</button>
        <button onclick="select('{{history_data.0.ship_id}}', 'onemonth')" class="btn btn-info">onemonth</button>
        <button onclick="select('{{history_data.0.ship_id}}','oneyear')" class="btn btn-info">oneyear</button>
    </div>
    <div class="col-md-10">
    {% for data in history_data %}
        <div class="row">
            <div class="col-md-12" id="{{ data.monitor_name }}_div" style="height: 46%"></div>
           <!--  <div class="col-md-4" id="result_left">
                <table id="{{ data.monitor_name }}_table" class="table">
                    <tr>
                        <th>速度</th>
                    </tr>
                    <tr>
                        <td id="speed" class="info">{{ data.monitor_data }}</td>
                    </tr>
                </table>
            </div> -->
        </div>
    {% endfor %}
    </div>
</div>
<script type="text/javascript">
    var dom_names     = [];
    var monitor_datas = [];
    var options       = [];
    var ship_id       = [];
    var charts        = [];
    var app           = [];
    var data          = [];
    var now           = +new Date(2009, 9, 3);
    var oneDay        = 24 * 3600 * 1000;
    var value         = Math.random() * 1000;
    for (var i = 0; i < 10; i++) {
        data.push(randomData());
    }
    function get_option(subtitle, speed_data, oil_temperature_data){
        option = {
            title: {
                text: '动态数据+历史数据',
                subtext: subtitle+"(监控仪名：引擎名：船舶名)",
            },
            legend: {
                data:['speed', 'oil_temperature'],
                orient: 'vertical',
                left:'right',
                top: 'center',
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    animation: false
                }
            },
            xAxis: {
                type: 'time',
                splitLine: {
                    show: false
                }
            },
            yAxis: {
                type: 'value',
                boundaryGap: [0, '100%'],
                splitLine: {
                    show: false
                }
            },
            dataZoom: [
                {
                    show: true,
                    start: 94,
                    end: 100,
                    handleSize: 8
                },
                {
                    type: 'inside',
                    start: 94,
                    end: 100
                },
            ],
            series: [
                {
                    name: 'speed',
                    type: 'line',
                    showSymbol:false,
                    hoverAnimation: true,
                    data: speed_data,
                },
                {
                    name: 'oil_temperature',
                    type: 'line',
                    showSymbol:false,
                    hoverAnimation: true,
                    data: oil_temperature_data,
                },
            ]
        };
        return option;
    }
    function randomData(){
        now   = new Date(+now + oneDay);
        value = value + Math.random() * 21 - 10;
        return {
            name: now.toString(),
            value: [
                [now.getFullYear(), now.getMonth() + 1, now.getDate()].join('-'),
                Math.round(value)
            ]
        }
    }
    function charts_data(time_data, about_data){
        year      = time_data[1];
        m_d       = time_data[0];
        h_m_s     = time_data[2];
        temp_h    = h_m_s.split(':')[0];
        date_type = h_m_s.split(':')[1].split(' ')[1];
        m         = h_m_s.split(':')[1].split(' ')[0];
        if(date_type == 'p.m.')
        {
            h = parseInt(temp_h) + 12;
            h = h.toString();
        }
        else{
            h = temp_h;
        }
        temp_m_d   = m_d.split(" ");
        temp_month = temp_m_d[0];
        day        = temp_m_d[1];
        switch(temp_month)
        {
            case 'Jan.':
                month = 0;
                break;
            case 'Feb.':
                month = 1;
                break;
            case 'March':
                month = 2;
                break;
            case 'April':
                month = 3;
                break;
            case 'May':
                month = 4;
                break;
            case 'June':
                month = 5;
                break;
            case 'July':
                month = 6;
                break;
            case 'Aug.':
                month = 7;
                break;
            case 'Sept.':
                month = 8;
                break;
            case 'Oct.':
                month = 9;
                break;
            case 'Nov.':
                month = 10;
                break;
            case 'Dec.':
                month = 11;
                break;
            default:
                month = 0;
                break;
        }
        now = new Date(year, month, day, h, m);
        return {
            name: now.toString(),
            value: [
                [now.getFullYear(), now.getMonth() + 1, now.getDate()].join('-'),
                about_data
            ]
        }
    }
    function update_charts_data(time_data, about_data){
        temp_ymd = time_data[0].split('-')
        year = temp_ymd[0];
        month = temp_ymd[1];
        day = temp_ymd[2];
        temp_hms = time_data[1].split(':');
        h = temp_hms[0];
        m = temp_hms[1];
        now = new Date(year, month-1, day, h, m);
        return {
            name: now.toString(),
            value:[
                [now.getFullYear(), now.getMonth() + 1, now.getDate()].join('-'),
                about_data
            ]
        }
    }
</script>
{% for x in history_data %}
<script type="text/javascript">
    var generation_data_time = [];
    var speed                = [];
    var temp_data            = [];
    var oil_temperature      = [];
    var water_temperature    = [];
    dom_name                 = '{{ x.monitor_name }}_div';
    dom_names.push(dom_name);
    ship_id.push('{{ x.ship_id }}');
</script>
    {% for k in x.monitor_data %}
    <script type="text/javascript">
        temp_date = '{{ k.generation_data_time }}'.split(',');
        generation_data_time.push(temp_date);
        speed.push({{ k.speed }});
        oil_temperature.push({{ k.oil_temperature }});
        water_temperature.push({{ k.water_temperature }});
    </script>
    {% endfor %}
    <script type="text/javascript">
        temp_data.push(generation_data_time, speed, oil_temperature, water_temperature);
        monitor_datas.push(temp_data);
    </script>
{% endfor %}
<script type="text/javascript">
    function init(){
        for(var j=0;j<dom_names.length;j++){
            var speed_data             = [];
            var oil_temperature_data   = [];
            var water_temperature_data = [];
            charts.push(echarts.init(document.getElementById(dom_names[j])));
            for(var i=0;i<monitor_datas[j][0].length;i++){
                YMD                         = monitor_datas[j][0][i];
                name                        = [YMD[0], YMD[1], YMD[2]].join('-');
                temp_speed_data             = charts_data(YMD, monitor_datas[j][1][i]);
                temp_oil_temperature_data   = charts_data(YMD, monitor_datas[j][2][i]);
                temp_water_temperature_data = charts_data(YMD, monitor_datas[j][3][i]);
                speed_data.push(temp_speed_data);
                oil_temperature_data.push(temp_oil_temperature_data);
                water_temperature_data.push(temp_water_temperature_data);
            }
            options.push(get_option(dom_names[j].split('_')[0], speed_data, oil_temperature_data));
            charts[j].setOption(options[j]);
        }
    }

init();
$(document).ready(function(){
    var url = '/map/events2/' + ship_id[0];
    var source = new EventSource(url);
    var show_data_json
    source.addEventListener("date", function(e){
        show_data = JSON.parse(e.data);
        for(var j=0;j<show_data.length;j++){
            show_data_json         = JSON.parse(show_data[j]);
            speed                  = show_data_json['monitor_data'].speed;
            oil_temperature        = show_data_json['monitor_data'].oil_temperature;
            water_temperature      = show_data_json['monitor_data'].water_temperature;
            generation_data_time   = show_data_json['monitor_data'].generation_data_time;
            generation_data_time   = generation_data_time.split("T");
            YMD                    = generation_data_time[0];
            HMS                    = generation_data_time[1].split("Z")[0];
            speed_data             = update_charts_data([YMD, HMS], speed);
            oil_temperature_data   = update_charts_data([YMD, HMS], oil_temperature);
            water_temperature_data = update_charts_data([YMD, HMS], water_temperature);
            temp_option            = charts[j].getOption()
            last_time_name = temp_option.series[0].data[0].name;
            now_time_name = speed_data.name;
            // if(now_time_name != last_time_name){
            //     temp_option.series[0].data.shift();
            //     temp_option.series[1].data.shift();
            //     temp_option.series[0].data.push(speed_data);
            //     temp_option.series[1].data.push(oil_temperature_data);
            //     charts[j].setOption({
            //         series:[
            //             {data:temp_option.series[0].data}, 
            //             {data:temp_option.series[1].data}
            //             ]
            //     });
            // }

        }
    });
});

function select(ship_id, param){
    urls = '/map/history_data/'+ship_id+'/'+param+'/';
    for(var i=0;i<charts.length;i++){
        charts[i].showLoading();
    }
    $.ajax({
        url: urls,
        dataType: 'json',
        success: function(data){
            var i = setTimeout('hidding_loading()',1000);
            select_history_data(data);
            // alert(JSON.parse(JSON.parse(data[0].monitor_data)[0])['speed']);
        },
        error:function(data){
            $.alert({
            title: '提醒!',
            content: "非常抱歉！没有找到定位相关数据",
            theme: 'material',
            animationSpeed: 300,
            autoClose: 'confirm|2000',
            });
        }
    });
}

function hidding_loading()
{
    for (var i = 0; i < charts.length; i++)
    {
        charts[i].hideLoading();
    }
}

function select_history_data(data){

    for(var i=0;i<data.length;i++){
        var speed_data             = [];
        var oil_temperature_data   = [];
        var water_temperature_data = [];
        monitor_name = data[i].monitor_name;
        monitor_data = JSON.parse(data[i].monitor_data);
        for(var j=0;j<monitor_data.length;j++){
            monitor_data_x = JSON.parse(monitor_data[j]);
            YMD = monitor_data_x.generation_data_time.split('T')[0]
            HMS = monitor_data_x.generation_data_time.split('T')[1].split('Z')[0]
            temp_speed_data             = update_charts_data([YMD, HMS], monitor_data_x['speed']);
            temp_oil_temperature_data   = update_charts_data([YMD, HMS], monitor_data_x['oil_temperature']);
            temp_water_temperature_data = update_charts_data([YMD, HMS], monitor_data_x['water_temperature']);
            speed_data.push(temp_speed_data);
            oil_temperature_data.push(temp_oil_temperature_data);
            water_temperature_data.push(temp_water_temperature_data);
        }
        charts[i].setOption({
                    series:[
                        {data:speed_data}, 
                        {data:oil_temperature_data}
                        ]
                });
    }
}
</script>
</body>
</html>
{% endblock %}
